package com.quanxiaoha.weblog.admin.utils;

import com.quanxiaoha.weblog.admin.config.MinioConfig;
import com.quanxiaoha.weblog.admin.config.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;


    public String uploadFile(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if(file == null || file.getSize() == 0) {
            log.error("===> 文件上传异常， 文件大小为空");
            throw new RuntimeException("文件大小不能为空");
        }
        // 原始名称
        String originalFilename = file.getOriginalFilename();
        // ContentType
        String contentType = file.getContentType();
        // 生成存储对象的名字
        String key = UUID.randomUUID().toString().replace("-", "");
        // 获取文件的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 拼接上文件后缀，即为要存储的文件名
        String objectName = key + suffix;

        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);

        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(contentType)
                        .build());
        // 返回文件的访问链接
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + objectName;
        log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);
        return url;
    }
}
